<template>
  <!-- // 分配角色 -->
  <div>
    <el-tree
      ref="treeRef"
      node-key="id"
      :data="permissionList"
      :props="{label:'name'}"
      show-checkbox
      default-expand-all
      check-strictly
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranListTotreeList } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permIds: [],
      permissionList: []
    }
  },
  created() {
    // 获取所有角色权限
    this.loadPermissionList()
    //  根据id获取当前角色权限
    this.loadRoleDetail()
  },
  methods: {
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log(res, '根据id获取角色权限')
        this.permIds = res.data.permIds
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)
      } catch (error) {
        console.log(error)
      }
    },

    // 获取所有角色权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('权限列表', res)
        this.originList = res.data
        this.permissionList = tranListTotreeList(res.data)
      } catch (error) {
        console.log(error)
      }
    },
    // 更改权限
    async doSave() {
      try {
        const permIds = this.$refs.treeRef.getCheckedKeys()
        const res = await assignPerm({ id: this.curId, permIds: permIds })
        console.log('更改角色权限', res)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
    //   this.$emit('close')
      this.doSave()
    },
    hClose() {
      this.$emit('close')
    }
  }
}
</script>
